//
//  SectionListViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/30.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "SectionListViewController.h"
#import "NetworkingTool.h"
#import "NewsDetailSectionModel.h"
#import "SectionListCell.h"
#import <MJExtension/MJExtension.h>
#import "MainNavigationController.h"
#import "SectionViewController.h"

@interface SectionListViewController ()
/** story模型数组 */
@property (nonatomic, strong) NSMutableArray *sectionLists;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;

/** 重新加载按钮 */
@property (nonatomic, weak) UIButton *reloadBtn;
@end

@implementation SectionListViewController

static NSString *sectionListReuseID = @"sectionListCell";

#pragma mark - 懒加载
- (UIButton *)reloadBtn{
    if (!_reloadBtn) {
        UIButton *reloadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        reloadBtn.titleLabel.numberOfLines = 0;
        reloadBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        reloadBtn.hidden = YES;
        [reloadBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [reloadBtn setTitle:@"加载数据失败，点击重新加载" forState:(UIControlStateNormal)];
        [reloadBtn addTarget:self action:@selector(loadData) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:reloadBtn];
        _reloadBtn = reloadBtn;
    }
    return _reloadBtn;
}

- (NSMutableArray *)sectionLists{
    if (!_sectionLists) {
        _sectionLists = [NSMutableArray array];
    }
    return _sectionLists;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBarView.title = @"专栏";
    
    __weak typeof(self) weakSelf = self;
    [self.navBarView setBackBtnClickBlock:^(UIButton *btn) {
        MainNavigationController *mainNav = (MainNavigationController *)weakSelf.navigationController;
        !mainNav.backBtnBlock ? : mainNav.backBtnBlock();
    }];
    
    // 去除多余分隔线
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.rowHeight = 64;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SectionListCell class]) bundle:nil] forCellReuseIdentifier:sectionListReuseID];
    
    [self loadData];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return NO;
}

- (void)loadData{
    [self.sectionLists removeAllObjects];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://news-at.zhihu.com/api/3/sections"];
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id responseObj, NSError *error) {
        if (error) {
            self.tableView.hidden = YES;
            self.reloadBtn.hidden = NO;
            return;
        }
        self.tableView.hidden = NO;
        [self.reloadBtn removeFromSuperview];
        
        NSArray *sectionLists = [NewsDetailSectionModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
        [self.sectionLists addObjectsFromArray:sectionLists];
        [self.tableView reloadData];
    }];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.reloadBtn.frame = CGRectMake(20, (JKScreenH - 60) * 0.5, self.view.width - 40, 60);
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sectionLists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionListCell *cell = [tableView dequeueReusableCellWithIdentifier:sectionListReuseID];
    
    NewsDetailSectionModel *model = self.sectionLists[indexPath.row];
    
    cell.model = model;
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) {
        [cell changeToNightSkin];
        
    }else{
        [cell changeToDaySkin];
    }
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsDetailSectionModel *section = self.sectionLists[indexPath.row];
    SectionViewController *sectionVc = [[SectionViewController alloc] init];
    sectionVc.section = section;
    [self.navigationController pushViewController:sectionVc animated:YES];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.currentSkinModel = currentSkinModel;
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = JKNightSkinColor;
        [self.navBarView changeToNightSkin];
        
    }else{ // 日间模式
        self.view.backgroundColor = JKGlobalBgColor;
        [self.navBarView changeToDaySkin];
    }
    
    [self.tableView reloadData];
}
@end
